<template>
  <el-container>
    <div class="login-box" :style="bg">
      <div class="loginlogo"></div>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="6rem"
        label-position="left"
        class="demo-ruleForm"
      >
        <el-form-item label="账号:" prop="username" class="inp1">
          <el-input
            class="inp11"
            v-model="ruleForm.username"
            placeholder="请输入账号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password" class="inp1">
          <el-input
            type="password"
            v-model="ruleForm.password"
            class="inp11"
            placeholder="请输入密码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <div class="inp2">
          <el-input
            v-model="vc.code"
            type="text"
            style="width: 45%"
            class="inp11"
          ></el-input>
          <span class="img">
            <img :src="getimg" alt="验证码获取失败" @click="change" />
          </span>
        </div>
        <el-form-item class="btns">
          <el-button round size="small" @click="resetForm('ruleForm')"
            >重置</el-button
          >
          <el-button
            type="info"
            round
            plain
            size="small"
            :loading=loading
            @click="submitForm"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-container>
</template>


<script>
import axios from "../utils/axios";
import md5 from "js-md5";
export default {
  name: "Login",
  created() {
    //登录页面的背景轮播效果，按需引入此功能
    // this.bg.backgroundImage =
    //   "url(" +
    //   require("../assets/imgs/bg0" + new Date().getDay() + ".jpg") +
    //   ")";
    this.getVc();
    //enter登录
     var t = this;
      document.onkeydown = function(e){
        
      //enter的ASCII码是13
        if(e.keyCode == 13){
          t.submitForm()
        }
      }

  },
  data() {
    let validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    let validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      loading:false,
      userId:'',
      bg: {},
      getimg: "",
      vc: {
        serial: "",
        code: "",
      },
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
      },
    };
  },
  methods: {
     getInfo() {
      axios({
        method: "GET",
        url: "/sys/user/getLoginUser",
      }).then((response) => {
        if (response.code === 200) {
           localStorage.setItem('userId',response.data.id)
        }
      });
    },
    submitForm() {
      this.loading=true

      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //先校验验证码
          axios({
            method: "GET",
            url: "/sys/util/checkVc",
            params: this.vc,
          }).then((res) => {
            if (res.code == 200) {

             

              //请求登录
                 let loginData = {
            loginName: this.ruleForm.username,
            password: md5(this.ruleForm.password),
          };

          axios({
            method: "POST",
            url: "/sys/login",
            data: loginData,
          }).then((response) => {
            if (response.code === 200) {
              this.loading=false
       
              // 提示登录成功，跳转到首页界面
              this.$message.success("登录成功！");
              this.getInfo()
            
              // localStorage.setItem("token", JSON.stringify(response.list));
            
              localStorage.setItem("token", response.data.token);
             
              this.$router.push("/main/home");
            } else {
              this.$message.error(`登陆失败:${response.message}`);
              this.vc.code=''
              this.getVc()
            }
          });
            } else {
                this.loading=false
              this.$message(res.message);
              this.vc.code=''
              this.getVc()
            }
          });
       
        } else {
            this.loading=false
          this.$message.error("填写数据有误，请检查后重新登录");
          
        }
      });
    },
    resetForm(formName) {
      this.vc.code=''
      this.getVc()
      this.$refs[formName].resetFields();
    },
    //获取验证码
    getVc() {
      axios({
        method: "GET",
        url: "/sys/util/getImgVc",
      }).then((res) => {
        if (res.code == 200) {
          this.getimg = "data:image/png;base64," + res.data.img;
          this.vc.serial = res.data.serial;
        }
      });
    },
    //点击刷新验证码
    change(){
      this.getVc()
    },
   
  },
};
</script>

<style lang="less" scoped >
.el-container {
  width: 100%;
  height: 100vh;

  background-image: url("../assets/imgs/bg1.jpg");
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-box {
  width: 40rem;
  height: 35rem;
  background: rgba(0, 0, 0, 0.3);
  position: relative;

  border-radius: 20px 50px;
  box-shadow: #ddd 0 0 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.login-box .loginlogo {
  position: absolute;
  top: 0;
  transform: translateY(-70%);
  width: 100px;
  height: 100px;
  opacity: 0.55;

  background: url("../assets/logo.png") no-repeat center center white;
  background-size: 75px;
  box-shadow: #ddd 0 0 10px;

  border-radius: 50%;
}

.el-form {
  width: 300px;
  height: 160px;
}

.inp1 /deep/ .el-form-item__label {
  color: #fff;
}
.inp11 /deep/ .el-input__inner {
  color: #ffff;
  background-color: transparent;
  outline: none;
  border-top: 0;
  border-right: 0;
  border-left: 0;
  font-size: 1.89rem;

  border-bottom: 0.1rem solid #fff;
}
.btns {
  display: flex;
  justify-content: flex-end;
  // margin-left: 11px;
}
.el-button {
  background-color: transparent;
  color: #fff;
  font-size: 1.35rem;
}
.inp2 {
  display: flex;
  justify-content: space-between;
  font-size: 1.2rem;
  color: #fff;
  align-items: center;
  margin-left: 5.9rem;
  margin-bottom: 1rem;
}
.inp2 .img {
  display: block;

  width: 50%;
  height: 4rem;
  line-height: 4rem;
}
.inp2 .img img {
  width: 100%;
  height: 100%;
}
</style>